package com.cans.lightning.business.pms.service.impl;


import com.cans.lightning.business.core.constant.Constants;
import com.cans.lightning.business.pms.dto.SysUserDto;
import com.cans.lightning.business.pms.service.api.ISysMenuService;
import com.cans.lightning.business.pms.service.api.ISysUserService;
import com.cans.lightning.config.redis.RedisCache;
import com.cans.lightning.business.core.service.TokenService;
import com.cans.lightning.business.pms.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class SysLoginService {

    @Resource
    private TokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysMenuService sysMenuService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @return 结果
     */
    public String login(String username, String password, String code) {

        // 验证码的KEY
        String verifyKey = Constants.CAPTCHA_CODE_KEY + username;
        // 获取验证码的值 暂不处理验证码
        String captcha = redisCache.getCacheObject(verifyKey);
        // 验证以后删除验证码缓存
        redisCache.deleteObject(verifyKey);
        // 用户验证
        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SysUser loginUser = (SysUser) authentication.getPrincipal();
        sysMenuService.getUserMenuTree(loginUser);
        // 生成token
        return tokenService.createToken(new SysUserDto().create(loginUser));
    }

    /**
     * 登出
     */
    public void loginOut() {
        SysUser currentUser = userService.getCurrentUser();
        if(currentUser == null){
            return;
        }
        // 清除登陆信息
        tokenService.delLoginUser(currentUser.getId());
        // 删除相关缓存
        sysMenuService.removeUserMenuTree(currentUser);

    }
}
